package com.tekj.cxqcb.view.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import common.base.MainApplication;
import es.dmoral.toasty.Toasty;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.pay_result);
//        this.getWindow().getDecorView().setBackgroundColor(Color.TRANSPARENT);

//        MainApplication.api = WXAPIFactory.createWXAPI(this, MainApplication.APP_ID, false);
        try {
            MainApplication.api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        MainApplication.api.handleIntent(intent, this);
    }

    /**
     * description: 微信发送请求到第三方应用时，会回调到该方法
     */
    @Override
    public void onReq(BaseReq req) {
        Toast.makeText(this, "openid = " + req.openId, Toast.LENGTH_SHORT).show();

        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                Toast.makeText(this, "  COMMAND_GETMESSAGE_FROM_WX", Toast.LENGTH_SHORT).show();

                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                Toast.makeText(this, "  COMMAND_SHOWMESSAGE_FROM_WX", Toast.LENGTH_SHORT).show();

                break;
            case ConstantsAPI.COMMAND_LAUNCH_BY_WX:
                Toast.makeText(this, "Launch From Weixin", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }


    /**
     * description: 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
     */
    @Override
    public void onResp(BaseResp resp) {
        Logger.d("baseresp.getType = " + resp.getType() + "  resp.errCode = " + resp.errCode
                + "  resp.openId = " + resp.openId);
//        Toast.makeText(this, "baseresp.getType = " + resp.getType() + "  resp.errCode = " + resp.errCode
//                + "  resp.openId = " + resp.openId, Toast.LENGTH_SHORT).show();

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case RETURN_MSG_TYPE_LOGIN:
                        //拿到了微信返回的code,立马再去请求access_token
                        String code = ((SendAuth.Resp) resp).code;
                        String state = ((SendAuth.Resp) resp).state;
                        Logger.d("code = " + code + "  state = " + state);
                        //发起网络请求
                        initGetWxLoginInfo(code, state);
                        break;

                    case RETURN_MSG_TYPE_SHARE:
                        Toasty.normal(getApplicationContext(), "微信分享成功").show();
                        finish();
                        break;
                }

                break;
            case BaseResp.ErrCode.ERR_COMM:
                Toasty.error(getApplicationContext(), "ERR_COMM").show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (RETURN_MSG_TYPE_SHARE == resp.getType()) {
                    Toasty.error(getApplicationContext(), "分享失败").show();
                    finish();
                } else {
                    String state = ((SendAuth.Resp) resp).state;
                    //第三方登录
                    if (state.equals("wxlogin")) {
                        Toasty.error(getApplicationContext(), "登录失败").show();
                    }  //数据绑定
                    if (state.equals("wxbinding")) {
                        Toasty.error(getApplicationContext(), "绑定失败").show();
                    }
                }
                break;
            case BaseResp.ErrCode.ERR_SENT_FAILED:
                Toasty.error(getApplicationContext(), "ERR_SENT_FAILED").show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toasty.error(getApplicationContext(), "ERR_AUTH_DENIED").show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                Toasty.error(getApplicationContext(), "ERR_UNSUPPORT").show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_BAN:
                Toasty.error(getApplicationContext(), "签名异常").show();
                finish();
                break;

            default:
                Logger.d("default");
                break;
        }
    }

    /**
     * description: 请求微信获取信息
     */
    private void initGetWxLoginInfo(final String code, final String state) {
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
//        String Url = "https://api.weixin.qq.com/sns/oauth2/access_token";
//        OkGo.<String>get(Url)
//                .tag(this)
//                .params("appid", MyApplication.WeixinAppID)
//                .params("secret", "cf4acb1623660b5af9baecb80bcfe7cc")
//                .params("code", code)
//                .params("grant_type", "authorization_code")

//        /**
//         * 此处服务器封装，因为secret参数是可变的
//         */
//        String Url = Urls.Weixin_access_token + code;
//        OkGo.<String>get(Url)
//                .tag(this)
////                .params("code", code)
//
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
//                        Logger.d("code>>>" + response.code() + "  body>>>" + response.body().toString());
////                        Toasty.success(getApplicationContext(), "code>>>" + response.code() + "  body>>>" + response.body().toString()).show();
//                        if (response.code() == 200) {
//                            try {
//                                GetWxLoginInfo bean = new Gson().fromJson(response.body().toString().trim(), GetWxLoginInfo.class);//Gson转Bean
//                                String key = bean.getOpenid();
//                                int kind = 2;//1微博 2微信 3QQ
//
//                                //第三方登录
//                                if (state.equals("wxlogin")) {
//                                    try {
//                                        new DoThreeLoginAction(WXEntryActivity.this, null, kind, key);//第三方登录catch (Exception ex) {
//                                        LoginActivity.mLoginActivity.finish();
//                                    } catch (Exception ex) {
//                                        Logger.e(ex.getMessage());
//                                        Toasty.error(getApplicationContext(), "ERROR:1002执行异常！").show();
//                                    }
//                                }
//                                //数据绑定
//                                if (state.equals("wxbinding")) {
//                                    new DoThreeBindingAction(new DoThreeBindingAction.OnFinishListener() {
//                                        @Override
//                                        public void onSuccess() {
//                                            BindAccountActivity.mBindAccountActivity.Init();//刷新绑定页面UI
//                                            finish();
//                                        }
//
//                                        @Override
//                                        public void onError() {
//                                            finish();
//                                        }
//                                    }, WXEntryActivity.this, kind, key);
//                                }
//
//
//                            } catch (Exception ex) {
//                                Logger.e(ex.getMessage());
//                                Toasty.error(getApplicationContext(), "ERROR:1001解析异常！").show();
//                            }
//                        } else {
//                            Toasty.error(getApplicationContext(), "code>>>" + response.code() + "  body>>>" + response.body().toString()).show();
//                        }
//                    }
//
//                    @Override
//                    public void onError(com.lzy.okgo.model.Response<String> response) {
//                        Logger.e("onError>>>" + response.message());
//
//                    }
//
//                });


    }


}